package com.ttxs.fileformathandling.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ttxs.apicommon.model.entity.UserApiInfo;
import com.ttxs.fileformathandling.common.ErrorCode;
import com.ttxs.fileformathandling.exception.BusinessException;

import com.ttxs.fileformathandling.service.UserApiInfoService;
import com.ttxs.fileformathandling.mapper.UserApiInfoMapper;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author cwt
 * @description 针对表【user_api_info(用户接口关联表)】的数据库操作Service实现
 * @createDate 2023-06-09 20:22:31
 */
@Service
public class UserApiInfoServiceImpl extends ServiceImpl<UserApiInfoMapper, UserApiInfo>
        implements UserApiInfoService {

    @Resource
    private UserApiInfoMapper userApiInfoMapper;

    @Override
    public void validUserApiInfo(UserApiInfo userApiInfo, boolean add) {
        if (userApiInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long apiId = userApiInfo.getApiId();
        long userId = userApiInfo.getUserId();
        if (add) {
            if (apiId <= 0 || userId <= 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户或接口不存在");
            }
        }
    }

    @Override
    public boolean validExist(long userId, long apiId) {
        QueryWrapper<UserApiInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(userId > 0, "userId", userId);
        queryWrapper.eq(apiId > 0, "apiId", apiId);
        UserApiInfo userApi = userApiInfoMapper.selectOne(queryWrapper);
        if (userApi == null) {
            UserApiInfo userApiInfo = new UserApiInfo();
            userApiInfo.setUserId(userId);
            userApiInfo.setApiId(apiId);
            userApiInfo.setTotalNum(1);
            return this.save(userApiInfo);
        }
        return true;
    }

    @Override
    public boolean invokeCount(long apiId, long userId) {
        if (apiId <= 0 || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户或接口不存在");
        }
        UpdateWrapper<UserApiInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("apiId", apiId);
        updateWrapper.eq("userId", userId);
        QueryWrapper<UserApiInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("apiId", apiId);
        queryWrapper.eq("userId", userId);
        UserApiInfo userApiInfo = userApiInfoMapper.selectOne(queryWrapper);
        if (userApiInfo.getLeftNum() <= 0) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "你调用该接口的次数已经用完");
        }
        //todo  加锁
        updateWrapper.setSql("leftNum = leftNum -1, totalNum = totalNum + 1");
        return this.update(updateWrapper);
    }
}




